/*
 * Copyright 2018-2021 guerlab.net and other contributors.
 *
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.guerlab.smart.pay.web.wx;

import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.impl.WxPayServiceApacheHttpImpl;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.guerlab.commons.exception.ApplicationException;
import net.guerlab.commons.random.RandomUtil;
import net.guerlab.smart.pay.service.properties.PayProperties;

import java.util.Base64;

/**
 * 微信支付服务
 *
 * @author guer
 */
@Slf4j
@Getter
public class WxPayService extends WxPayServiceApacheHttpImpl {

    private final PayProperties payProperties;

    private final net.guerlab.smart.pay.service.entity.WxPayConfig properties;

    public WxPayService(PayProperties payProperties, net.guerlab.smart.pay.service.entity.WxPayConfig wxPayConfig) {
        this.payProperties = payProperties;
        this.properties = wxPayConfig;
        config = new WxPayConfig();
        config.setAppId(properties.getAppId());
        config.setMchId(properties.getMchId());
        config.setMchKey(properties.getMchKey());
        config.setSubAppId(properties.getSubAppId());
        config.setSubMchId(properties.getSubMchId());
        config.setKeyContent(Base64.getDecoder().decode(properties.getKeyContentBase64()));
    }

    @Override
    public <T> T createOrder(WxPayUnifiedOrderRequest request) {
        request.setAppid(properties.getAppId());
        request.setMchId(properties.getMchId());
        request.setSubAppId(properties.getSubAppId());
        request.setSubMchId(properties.getSubMchId());
        request.setNonceStr(RandomUtil.nextString(6));
        request.setNotifyUrl(payProperties.getNotifyUrl() + request.getNotifyUrl());

        try {
            return super.createOrder(request);
        } catch (WxPayException e) {
            String res = e.getErrCodeDes();
            if (res == null) {
                res = e.getMessage();
            }
            log.debug(e.getMessage(), e);
            throw new ApplicationException(res);
        }
    }
}
